package com.tech.koufu.ui.activity.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.EntrustStock;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.adapter.TradeAdapter;
import com.tech.koufu.ui.view.BaseSimpleFragment;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable; 
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 当日历史记录
 * @author jl_luo
 *
 */
public class TradeDateFragment extends BaseSimpleFragment {
	private static final String TAG = TradeDateFragment.class.getName();
	private View rootView;
	private int page = 1;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView; 
	private TradeAdapter mAdapter;
	private String userid,groupid;
	private MyApplication myApp;
	private Context context;
	private ArrayList<EntrustStock> datas;

//	private RequestQueue mQueue;  
//	CookieStringRequest stringRequest;
	private String digitalid;

	public static TradeDateFragment newInstance(int index,String userid,String groupid,String digitalid) {
		TradeDateFragment hf = new TradeDateFragment();
		Bundle bundle = new Bundle();
		bundle.putInt("index", index);
		bundle.putString("userid", userid);
		bundle.putString("groupid", groupid);
		bundle.putString("digitalid", digitalid);
		hf.setArguments(bundle); 
		return hf;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {Log.d(TAG, "~~~~~onCreateView~~~~~~");
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.lv_list_competition, container, false);   
			myApp = (MyApplication) getActivity().getApplication();
			context = getActivity().getApplicationContext();
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		initView();
		return rootView; 
	}

	private void initView() { 
		mPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);

		mAdapter = new TradeAdapter(context);
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
		Bundle bundle = getArguments();
		if(bundle!=null){
			userid = bundle.getString("userid");
			groupid = bundle.getString("groupid");
			digitalid = bundle.getString("digitalid");
			Log.d(TAG, userid+",groupid="+groupid+",digitalid="+digitalid);
		}
	}
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) { 
		super.onActivityCreated(savedInstanceState);
		initData();
	}
	private void initData(){
		datas = new ArrayList<EntrustStock>();
//		mQueue = Volley.newRequestQueue(context);  
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }   
//				loadHisEntrust();
		        loadHisDll();
			}
		}); 
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
	}
	/**
	 * dll调用接口
	 */
	private void loadHisDll(){
		String url = myApp.url + "Entrust.dll";
		final String t = KouFuTools.readTimeInfo(new String());
		CookieStringRequest stringRequest = new CookieStringRequest(Request.Method.POST, url,
				new Response.Listener<String>() {

					@Override
					public void onResponse(final String response) {
						// 0:220917473346,000006,深振业Ａ,c,11.52,1,09:17:47 ,,,已报;
						// htxh,stock_code,stock_name,entrust_bs,price,amount,time,cj_price,cj_time,status;
						Log.v(TAG, "~~~~~~~~~~response~~~~~");
						Log.v(TAG, response);
						try{
						if (response != null && !response.equals("")) {
							if (response.substring(0, 1).equals("0")) {  
									String ret = response.substring(2);
									String[] list = ret.split(";");
									for (String result : list) {
										String[] rs = result.split(",");
										EntrustStock stockInfo = new EntrustStock();
										stockInfo.htxh = rs[0];
										stockInfo.setStockId(rs[1]);
										stockInfo.setStockName(rs[2]);
										stockInfo.entrustBs = rs[3];
										stockInfo.price = (rs[4]);
										stockInfo.amount = (rs[5]);
										stockInfo.time = rs[6];
										stockInfo.cjPrice = rs[7];
										stockInfo.cjTime = rs[8];
										stockInfo.status = rs[9];
										datas.add(stockInfo);
									} 
									if(null!=datas && datas.size()>0){
										mAdapter.datas = datas;
										mAdapter.notifyDataSetChanged(); 
									}  
							} else if (response.substring(0, 1).equals("1")) {
								// 1:今日无委托纪录！ 
								Toast.makeText(myApp, response.substring(2),
										Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(myApp, "异常数据", Toast.LENGTH_SHORT)
									.show();
						}
						}catch(Exception e){
							e.printStackTrace();
						}finally{
							mPullToRefreshListView.onRefreshComplete();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						mPullToRefreshListView.onRefreshComplete();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", userid);
				params.put("type", "0");
				params.put("time", t);
				return params;
			}

		};
		String cookie = KouFuTools.descrypt(userid + t);
		stringRequest.setHeader(cookie);
		stringRequest.setCharset("gbk");
		stringRequest.setTag(TAG);
		RequestQueueSingleton.getInstance(context).addToRequestQueue(stringRequest); 
	}
	 
	@Override
	public void onStop() { 
		super.onStop();
		RequestQueueSingleton.getInstance(context).cancleAllReq(TAG);
	}

	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
//			Toast.makeText(context, position + "," + id, Toast.LENGTH_SHORT).show();
		}
	};
	
	
	
}
